package org.lvgo.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察的类
 *
 * @author lvgo
 * @version 1.0
 * @date 2018/9/21 0021 15:38
 */
public class Subject {

    private List<Observer> observers = new ArrayList<>();

    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    /**
     * 添加观察者对象(客户端)
     *
     * @param observer 观察者对象
     */
    public void attach(Observer observer) {
        observers.add(observer);
    }

    /**
     * 通知所有被观察者观察的对象
     */
    private void notifyAllObservers() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}
